import { JsonController, Body, Get, Post, Session, Action,UseInterceptor, Req, Res } from "routing-controllers";
import { config } from "../../config";
import { JsonResponseMiddlewares } from "../../middleware/JsonResponseMiddlewares";
import { UserServiceImpl } from "../../service/impl/UserServiceImpl";
import { Service, Inject } from "typedi";
import { UserLoginModel } from "../../model/UserLoginModel";
import {UserRegisterModel} from "../../model/UserRegisterModel";

@Service()
@JsonController(`${config.apiurl}/user`)
@UseInterceptor(JsonResponseMiddlewares)
export class UserControllerApi {


  @Inject()
  private userService: UserServiceImpl;


  /**
   * @api {get} /user/sendSmsCode  sendSmsCode
   * @apiDescription  用户登录的接口
   * @apiName userlogin
   * @apiGroup user
   * @apiParam {string} userphone 手机号
   * @apiSuccessExample {json} 请求成功的返回:
   *  {
   *      "status" : 200,
   *      "result" : {
   *           smsId: 92350325,
   *       }
   *  }
   * @apiErrorExample {json} 请求失败的返回
   * {
   *   "status":200,
   *   "result":{
   *     }
   * }
   * @apiSampleRequest http://geekhelp.cn/bmy/api/user/sendSmsCode
   * @apiVersion 1.0.0
   */
  @Post("/sendSmsCode")
  public async sendSmsCode (@Body() user): Promise<Object> {
    let data:Object = await this.userService.userSmsCodeService({
      userphone: user.userphone
    });
    //session.user = data
    return data
  }


  /**
   * @api {get} /user/login  login
   * @apiDescription  用户登录的接口
   * @apiName userlogin
   * @apiGroup user
   * @apiParam {string} userphone 手机号
   * @apiParam {string} smscode   激活码
   *
   * @apiSuccessExample {json} 请求成功的返回:
   *  {
   *      "status" : 200,
   *      "result" : {
   *           smsId: 92350325,
   *       }
   *  }
   * @apiErrorExample {json} 请求失败的返回
   * {
   *   "status":200,
   *   "result":{
   *     }
   * }
   * @apiSampleRequest http://geekhelp.cn/bmy/api/user/login
   * @apiVersion 1.0.0
   */
  @Post("/login")
  public async loginByMobilePhone (@Session() session, @Body() user: UserLoginModel): Promise<Object> {
    
    let userinfo:Object = await this.userService.userLoginByMobilePhone({
      userphone: user.userphone,
      smscode: user.smscode
    });
    console.log("userinfo[0]:",userinfo[0])
    session.user = userinfo[0]
    return userinfo
  }

  @Post("/addUser")
  public async addUser (@Session() session, @Body() user: UserRegisterModel): Promise<Object> {
    console.log(user)
    let userinfo:Object = await this.userService.userRegisterService(user);

    return userinfo
  }


  @Get("/Logout")
  public async Logout (@Session() session, @Req() request: any, @Res() response: any) {
    response.redirect("/")
    session.user = null;
    return { code: 200 }
  }
}